package com.ffcc.fitness.common.service.impl;

import com.ffcc.fitness.common.service.QRCodeService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * QR码生成服务实现类
 */
@Slf4j
@Service
public class QRCodeServiceImpl implements QRCodeService {

    @Value("${file-path}")
    private String basePath;

    // QR码尺寸
    private static final int QR_CODE_SIZE = 300;
    
    // QR码颜色
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;    @Override    public String generateMerchantQRCode(Long merchantId, String merchantName) {
        try {
            // 生成更简洁的商家二维码内容，提高扫码成功率
            String qrContent = String.format("健身器械交易平台\n商家: %s\n商家ID: %d\nwechatpay://pay", 
                merchantName, merchantId);
            
            log.info("生成商家QR码内容: {}", qrContent);
            
            // 生成唯一文件名
            String fileName = "merchant_qr_" + merchantId + "_" + System.currentTimeMillis();
            
            // 生成QR码
            return generateQRCode(qrContent, fileName, "qrcodes/merchant");
            
        } catch (Exception e) {
            log.error("为商家生成QR码失败: merchantId={}, merchantName={}", merchantId, merchantName, e);
            throw new RuntimeException("生成QR码失败", e);
        }
    }@Override
    public String generateOrderQRCode(Long merchantId, String merchantName, String equipmentName, 
                                     Integer quantity, String totalAmount) {
        try {
            // 生成简单文本格式的二维码内容，适合微信扫码
            StringBuilder qrContent = new StringBuilder();
            qrContent.append("总金额：").append(totalAmount).append(",\n");
            qrContent.append("商家名称：").append(merchantName).append(",\n");
            qrContent.append("商品名称：").append(equipmentName);
            
            if (quantity > 1) {
                qrContent.append(",\n数量：").append(quantity);
            }
            
            log.info("生成订单QR码内容: {}", qrContent.toString());
            
            // 生成唯一文件名，包含时间戳确保唯一性
            String fileName = "order_qr_" + merchantId + "_" + System.currentTimeMillis();
            
            // 生成QR码
            return generateQRCode(qrContent.toString(), fileName, "qrcodes/order");
            
        } catch (Exception e) {
            log.error("为订单生成QR码失败: merchantId={}, equipmentName={}, quantity={}, totalAmount={}", 
                     merchantId, equipmentName, quantity, totalAmount, e);
            throw new RuntimeException("生成订单QR码失败", e);
        }
    }

    @Override
    public String generateQRCode(String content, String fileName, String directory) {
        try {
            // 创建保存目录
            String fullDirectory = basePath + "/" + directory;
            File dir = new File(fullDirectory);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 设置QR码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);

            // 生成QR码
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, hints);

            // 创建图片
            BufferedImage image = new BufferedImage(QR_CODE_SIZE, QR_CODE_SIZE, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < QR_CODE_SIZE; x++) {
                for (int y = 0; y < QR_CODE_SIZE; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
                }
            }

            // 保存文件
            String fullFileName = fileName + ".png";
            String fullPath = fullDirectory + "/" + fullFileName;
            File outputFile = new File(fullPath);
            ImageIO.write(image, "PNG", outputFile);

            // 返回相对路径
            String relativePath = "/" + directory + "/" + fullFileName;
            log.info("QR码生成成功: content={}, path={}", content, relativePath);
            
            return relativePath;

        } catch (WriterException | IOException e) {
            log.error("生成QR码失败: content={}, fileName={}, directory={}", content, fileName, directory, e);
            throw new RuntimeException("生成QR码失败", e);
        }
    }
}
